/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package user;

import ejb.GestioneSediLocal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import jpa.Sede;

/**
 *
 * @author Administrator
 */
@ManagedBean(name = "SediBean")
@SessionScoped
public class SediBean {

    public static final int MAXROW = 20;

    @EJB
    GestioneSediLocal gs;
    private List<Sede> sedi;
    private int page;
    private int numTuple = -1;
    private int numPage;
    private boolean successivo;
    private boolean precedente;
    private String message;
    private int start;
    private int end;

    /**
     * Creates a new instance of HomeBean
     */
    public SediBean() {
        precedente = true;
        successivo = false;
        page = 0;
        numTuple = -1;
        numPage = 1;

    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isPrecedente() {
        return precedente;
    }

    public boolean isSuccessivo() {
        return successivo;
    }

    public int getPage() {
        return page;
    }

    public Collection<Sede> getSedi() {
        update();
        sedi = gs.listaSedi(start, end);
        return Collections.unmodifiableCollection(sedi);
    }

    private void update() {
        numTuple = gs.numeroSedi();
        if (numTuple == 0) {
            numPage = 1;
            return;
        }
        if (numTuple <= MAXROW) {
            successivo = true;
        }

        numPage = numTuple / MAXROW;
        if (numPage > 1) {
            successivo = false;
        }
        if (numTuple % MAXROW != 0) {
            numPage += 1;
        }
        start = page * MAXROW;
        end = ((page + 1) * MAXROW);

    }

    public String getPagine() {
        return " Pagina " + (page + 1) + " di " + numPage + " ";
    }

    public String precedente() {
        page--;
        if (page <= 0) {
            page = 0;
            precedente = true;

        }
        if (page < numPage) {
            successivo = false;
        }
        update();
        return "sedi";
    }

    public String successivo() {
        page++;
        if (page >= (numPage - 1)) {
            page = (numPage - 1);
            successivo = true;

        }
        if (page > 0) {
            precedente = false;
        }
        update();
        return "sedi";
    }

    public int getNumPage() {
        return numPage;
    }

    public void riempiDb() {
        gs.riempiDB();
    }

}
